package betSystems;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Vector;
import Entity.Iteratore;
import Entity.Schedina;
import Entity.Scommessa;
import Entity.Sistema;
import Entity.TriplaRisultato1X2;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.LineSeparator;
import java.io.File;
import java.io.FileOutputStream;
import java.text.NumberFormat;
import java.util.Date;

public class GastoneSimulator {

    private int maxdimriga;
    private int maxdimcolonna = 2;
    private double maxquota;
    private int puntataschedina;
    private int contatoresistemi = 0;
    private Scommessa[][] tabella;
    private Vector<Sistema> sistemi = new Vector<Sistema>();
    //private int numeroSemplifcate = 1;

    public void calcolaSistemi() throws Exception {

        sistemi.clear();

        Iteratore p0 = new Iteratore();
        Iteratore p1 = new Iteratore();
        Iteratore p2 = new Iteratore();
        Iteratore p3 = new Iteratore();
        Iteratore p4 = new Iteratore();

        Vector<Iteratore> iteratori = new Vector<Iteratore>(5);
        iteratori.add(p0);
        iteratori.add(p1);
        iteratori.add(p2);
        iteratori.add(p3);
        iteratori.add(p4);

        if (primaPosizioneValida(0, 0, 0, iteratori) == false) {
            return;
        }

        checkPartite(iteratori);

        int ultimo = 4;
        int riga, colonna;

        while (ultimo != -1) {

            if (iteratori.get(ultimo).getPos_colonna() == maxdimcolonna) {
                riga = iteratori.get(ultimo).getPos_riga() + 1;
                colonna = 0;
            } else {
                colonna = iteratori.get(ultimo).getPos_colonna() + 1;
                riga = iteratori.get(ultimo).getPos_riga();
            }

            if (primaPosizioneValida(riga, colonna, ultimo, iteratori)) {
                checkPartite(iteratori);
                ultimo = 4;

            } else {
                ultimo--;
            }

        }


    }

    public Vector<Sistema> cercaFissa(Scommessa fissa) {

        Vector<Sistema> tmp = new Vector<Sistema>();

        for (Sistema sis : getSistemi()) {
            if (sis.getFissa().equals(fissa)) {
                tmp.add(sis);
            }
        }

        return tmp;
    }

    public Vector<Sistema> cercaPartite(Vector<Sistema> database, Vector<Scommessa> daCercare) {

        Vector<Sistema> tmp = new Vector<Sistema>();

        for (Sistema sis : database) {
            if (sis.getPartite().containsAll(daCercare)) {
                tmp.add(sis);
            }
        }

        return tmp;
    }

    public void printSistemi(Vector<Sistema> vec, File output) {

        Document document = new Document();
        float[] widths = {4f, 1f, 1f, 1f};
        PdfPTable table;
        PdfPCell cell;
        Font font1 = new Font(Font.FontFamily.TIMES_ROMAN, 13);
        Font font2 = new Font(Font.FontFamily.TIMES_ROMAN, 10);

        if (! output.getName().endsWith(".pdf")){
            output = new File(output.getAbsolutePath() + ".pdf");
        }

        try {
            PdfWriter.getInstance(document,
                    new FileOutputStream(output));

            document.addTitle("Sistema per scommesse sportive");
            document.addSubject("Sistema vittoria sbagliando due partite su cinque");
            document.addKeywords("scommesse, sistema, gastone");
            document.addAuthor("Beccari Francesco");
            document.addHeader("Expires", "0");
            document.open();


            int contatore = 1, num = 1;

            for (Sistema s : vec) {

                document.add(new Paragraph("Sistema " + contatore, font1));
                document.add(Chunk.NEWLINE);
                document.add(new LineSeparator());
                document.add(Chunk.NEWLINE);

                table = new PdfPTable(1);

                cell = new PdfPCell(new Paragraph(
                        "Partite", font2));
                cell.setBorder(Rectangle.TOP | Rectangle.BOTTOM | Rectangle.LEFT | Rectangle.RIGHT);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);

                table.addCell(cell);

                document.add(table);

                table = new PdfPTable(widths);

                for (Scommessa scommessa : s.getPartite()) {

                    cell = new PdfPCell(new Paragraph(scommessa.getEvento(), font2));

                    if (num == 1) {
                        cell.setBorder(Rectangle.TOP | Rectangle.LEFT);
                    } else {
                        if (num == 5) {
                            cell.setBorder(Rectangle.BOTTOM | Rectangle.LEFT);
                        } else {
                            cell.setBorder(Rectangle.LEFT);
                        }
                    }
                    table.addCell(cell);

                    cell = new PdfPCell(new Paragraph(scommessa.getTipo().toString(), font2));
                    cell.setBorder(Rectangle.NO_BORDER);
                    if (num == 1) {
                        cell.setBorder(Rectangle.TOP);
                    } else {
                        if (num == 5) {
                            cell.setBorder(Rectangle.BOTTOM);
                        }
                    }
                    table.addCell(cell);

                    cell = new PdfPCell(new Paragraph(Double.toString(scommessa.getQuota()), font2));
                    cell.setBorder(Rectangle.NO_BORDER);
                    if (num == 1) {
                        cell.setBorder(Rectangle.TOP);
                    } else {
                        if (num == 5) {
                            cell.setBorder(Rectangle.BOTTOM);
                        }
                    }
                    table.addCell(cell);

                    cell = new PdfPCell(new Paragraph(
                            NumberFormat.getInstance().format(scommessa.getProbabilita() * 100) + " %", font2));
                    if (num == 1) {
                        cell.setBorder(Rectangle.TOP | Rectangle.RIGHT);
                    } else {
                        if (num == 5) {
                            cell.setBorder(Rectangle.BOTTOM | Rectangle.RIGHT);
                        } else {
                            cell.setBorder(Rectangle.RIGHT);
                        }
                    }
                    table.addCell(cell);

                    num++;

                }

                num = 1;

                document.add(table);

                table = new PdfPTable(widths);

                document.add(Chunk.NEWLINE);

                table = new PdfPTable(1);

                cell = new PdfPCell(new Paragraph(
                        "Schedine", font2));
                cell.setBorder(Rectangle.TOP | Rectangle.BOTTOM | Rectangle.LEFT | Rectangle.RIGHT);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);

                table.addCell(cell);

                document.add(table);


                for (Schedina schedina : s.getSchedine()) {

                    table = new PdfPTable(widths);
                    cell = new PdfPCell(new Paragraph("Schedina " + String.valueOf(num), font2));
                    num++;
                    cell.setBorder(Rectangle.BOX);
                    cell.setColspan(4);
                    table.addCell(cell);

                    for (Scommessa scommessa : schedina.getScommesse()) {

                        cell = new PdfPCell(new Paragraph(scommessa.getEvento(), font2));
                        cell.setBorder(Rectangle.LEFT);
                        table.addCell(cell);

                        cell = new PdfPCell(new Paragraph(scommessa.getTipo().toString(), font2));
                        cell.setBorder(Rectangle.NO_BORDER);
                        table.addCell(cell);

                        cell = new PdfPCell(new Paragraph(Double.toString(scommessa.getQuota()), font2));
                        cell.setBorder(Rectangle.NO_BORDER);
                        table.addCell(cell);

                        cell = new PdfPCell(new Paragraph(NumberFormat.getInstance().
                                format(scommessa.getProbabilita() * 100) + " %", font2));
                        cell.setBorder(Rectangle.RIGHT);
                        table.addCell(cell);


                    }

                    cell = new PdfPCell(new Paragraph("Vittoria : " + String.valueOf(
                            NumberFormat.getInstance().format(
                            ((schedina.getVittoria() - 4) * s.getPuntata()))) + " €", font2));
                    cell.setBorder(Rectangle.BOX);
                    cell.setColspan(4);
                    table.addCell(cell);

                    document.add(table);

                }

                document.add(Chunk.NEWLINE);

                table = new PdfPTable(1);

                cell = new PdfPCell(new Paragraph(
                        "Vittorie", font2));
                cell.setBorder(Rectangle.TOP | Rectangle.BOTTOM | Rectangle.LEFT | Rectangle.RIGHT);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);

                table.addCell(cell);

                document.add(table);

                num = 1;
                float[] widths2 = {3f, 1f, 2f};
                table = new PdfPTable(widths2);

                for (int i = 0; i < 6; i++) {

                    if (num == 1) {
                        cell = new PdfPCell(new Paragraph("Sbagliando solo ", font2));
                        cell.setColspan(2);
                        cell.setBorder(Rectangle.TOP | Rectangle.LEFT | Rectangle.BOTTOM);
                    } else {
                        if (num == 6) {
                            cell = new PdfPCell(new Paragraph("Indovinandole tutte ", font2));
                            cell.setColspan(2);
                            cell.setBorder(Rectangle.TOP | Rectangle.BOTTOM | Rectangle.LEFT);
                        } else {

                            cell = new PdfPCell(new Paragraph(s.getPartite().get(6 - num).getEvento(), font2));
                            cell.setBorder(Rectangle.LEFT);
                            table.addCell(cell);

                            cell = new PdfPCell(new Paragraph(s.getPartite().get(6 - num).getTipo().toString(), font2));
                            cell.setBorder(Rectangle.RIGHT);


                        }
                    }
                    table.addCell(cell);

                    if (num == 1) {
                        cell = new PdfPCell(new Paragraph(" si vince ", font2));
                        cell.setBorder(Rectangle.LEFT | Rectangle.TOP | Rectangle.RIGHT | Rectangle.BOTTOM);
                    } else {
                        cell = new PdfPCell(new Paragraph(String.valueOf(
                                NumberFormat.getInstance().format((s.getVittorie().get(num - 2) - 4)
                                * s.getPuntata()) + " €"), font2));
                        if (num == 6) {
                            cell.setBorder(Rectangle.LEFT | Rectangle.TOP | Rectangle.BOTTOM | Rectangle.RIGHT);
                        } else {

                            cell.setBorder(Rectangle.RIGHT);
                        }
                    }
                    table.addCell(cell);

                    num++;

                }

                document.add(table);

                document.add(Chunk.NEWLINE);

                table = new PdfPTable(1);

                cell = new PdfPCell(new Paragraph(
                        "Probabilità di vittoria "
                        + String.valueOf(
                        NumberFormat.getInstance().format(
                        s.getProbabilitaVittoria() * 100) + "%"), font2));
                cell.setBorder(Rectangle.TOP | Rectangle.BOTTOM | Rectangle.LEFT | Rectangle.RIGHT);

                table.addCell(cell);

                document.add(table);

                num = 1;

                document.newPage();

                table = new PdfPTable(widths);
                contatore++;


            }



        } catch (Exception e) {

            e.printStackTrace();

        }
        document.close();


    }

    public void numeroPartite(String string) {

        FileReader inputFile = null;
        int cont = 0;
        String read = "";

        try {

            inputFile = new FileReader(string);

            BufferedReader buff = new BufferedReader(inputFile);
            read = buff.readLine();

            while (read != null) {
                if (!read.startsWith("Inizio")) {
                    cont++;
                }
                read = buff.readLine();
            }

            maxdimriga = cont - 1;

            tabella = new Scommessa[maxdimriga + 1][maxdimcolonna + 1];


        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public void loadPartite(String string) {

        FileReader inputFile = null;

        int contatoreQuote = 1;

        try {

            inputFile = new FileReader(string);

            BufferedReader buff = new BufferedReader(inputFile);

            String read = buff.readLine(), evento = "", quota = "";
            double q1 = 0, q2 = 0, q3 = 0;
            int contatoredilineette = 0, contatoreditab = 0, contatorediquote = 0;
            int riga = 0;

            while (read != null) {

                if (read.startsWith("Inizio")) {
                } else {

                    while (contatoredilineette != 2) {

                        if (read.charAt(0) == '-') {
                            contatoredilineette++;
                        }
                        read = read.substring(1);

                    }

                    read = read.substring(1);

                    while (read.charAt(0) != '\t') {
                        evento = evento + read.charAt(0);
                        read = read.substring(1);
                    }

                    while (contatoreditab != 4) {
                        if (read.charAt(0) == '\t') {
                            contatoreditab++;
                        }
                        read = read.substring(1);
                    }

                    read = read.substring(2);

                    while (contatorediquote != 3) {

                        while (read.charAt(0) != '\t') {
                            quota = quota + read.charAt(0);
                            read = read.substring(1);
                        }

                        quota = quota.replace(',', '.');

                        if (contatorediquote == 0) {
                            q1 = Double.parseDouble(quota);
                        }
                        if (contatorediquote == 1) {
                            q2 = Double.parseDouble(quota);
                        }
                        if (contatorediquote == 2) {
                            q3 = Double.parseDouble(quota);
                        }

                        contatorediquote++;
                        read = read.substring(1);
                        quota = "";
                    }

                    tabella[riga][0] = new Scommessa(contatoreQuote, q1,
                            evento.trim(), TriplaRisultato1X2.Uno);
                    contatoreQuote++;
                    tabella[riga][1] = new Scommessa(contatoreQuote, q2,
                            evento.trim(), TriplaRisultato1X2.X);
                    contatoreQuote++;
                    tabella[riga][2] = new Scommessa(contatoreQuote, q3,
                            evento.trim(), TriplaRisultato1X2.Due);
                    tabella[riga][0].calcolaProbabilita(q2, q3);
                    tabella[riga][1].calcolaProbabilita(q1, q3);
                    tabella[riga][2].calcolaProbabilita(q1, q2);

                    contatoreQuote++;
                    riga++;

                }

                read = buff.readLine();
                contatoredilineette = 0;
                contatoreditab = 0;
                contatorediquote = 0;
                evento = "";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void checkPartite(Vector<Iteratore> iteratori) throws Exception {

        Vector<Scommessa> v = new Vector<Scommessa>(5);

        for (int i = 0; i < iteratori.size(); i++) {
            v.add(tabella[iteratori.get(i).getPos_riga()][iteratori.get(i).getPos_colonna()]);
        }

        Sistema nuovo = new Sistema(v, puntataschedina);

        boolean giaPresente = false;
        Vector<Integer> vnuovo = new Vector<Integer>();
        Vector<Integer> vsis = new Vector<Integer>();
        Sistema simile = null;

        for (Scommessa scm : nuovo.getPartite()) {
            vnuovo.add(scm.getId());
        }

        for (Sistema o1 : sistemi) {

            simile = null;

            if (o1.getFissa().getId() == vnuovo.get(0)) {

                for (Scommessa scm : o1.getPartite()) {
                    vsis.add(scm.getId());
                }

                if (vsis.containsAll(vnuovo)) {
                    giaPresente = true;
                    //numeroSemplifcate++;
                    simile = o1;
                    break;
                }

            }

            vsis.clear();

        }



        if (!giaPresente) {
            sistemi.add(nuovo);
            contatoresistemi++;
        } else {
            // Vittoria massima
            if (nuovo.getVittorie().get(4) > simile.getVittorie().get(4)) {
                sistemi.remove(simile);
                sistemi.add(nuovo);
            }
        }


    }

    public boolean primaPosizioneValida(int riga, int colonna,
            int iteratore, Vector<Iteratore> iteratori) {

        boolean trovata = false;
        int riga_tmp, colonna_tmp;

        riga_tmp = riga;
        colonna_tmp = colonna;

        while (trovata == false && riga_tmp <= maxdimriga) {

            if (iteratore == 0) {
                if (tabella[riga_tmp][colonna_tmp].getQuota() >= 1.4
                        && tabella[riga_tmp][colonna_tmp].getQuota() <= maxquota) {
                    if (iteratori.get(1).getPos_riga() != riga_tmp
                            && iteratori.get(2).getPos_riga() != riga_tmp
                            && iteratori.get(3).getPos_riga() != riga_tmp
                            && iteratori.get(4).getPos_riga() != riga_tmp) {
                        trovata = true;
                    }
                }
            }

            if (iteratore == 1) {
                if (tabella[riga_tmp][colonna_tmp].getQuota() >= 1.5
                        && tabella[riga_tmp][colonna_tmp].getQuota() <= maxquota) {
                    if (iteratori.get(0).getPos_riga() != riga_tmp
                            && iteratori.get(2).getPos_riga() != riga_tmp
                            && iteratori.get(3).getPos_riga() != riga_tmp
                            && iteratori.get(4).getPos_riga() != riga_tmp) {
                        trovata = true;
                    }
                }
            }

            if (iteratore == 2) {
                if (tabella[riga_tmp][colonna_tmp].getQuota() >= (4 / (tabella[iteratori.get(0).getPos_riga()][iteratori.get(0).getPos_colonna()].getQuota() * tabella[iteratori.get(1).getPos_riga()][iteratori.get(1).getPos_colonna()].getQuota()))
                        && tabella[riga_tmp][colonna_tmp].getQuota() <= maxquota) {
                    if (iteratori.get(0).getPos_riga() != riga_tmp
                            && iteratori.get(1).getPos_riga() != riga_tmp
                            && iteratori.get(3).getPos_riga() != riga_tmp
                            && iteratori.get(4).getPos_riga() != riga_tmp) {
                        trovata = true;
                    }
                }
            }

            if (iteratore == 3) {
                if (tabella[riga_tmp][colonna_tmp].getQuota() >= (4 / (tabella[iteratori.get(0).getPos_riga()][iteratori.get(0).getPos_colonna()].getQuota() * tabella[iteratori.get(1).getPos_riga()][iteratori.get(1).getPos_colonna()].getQuota()))
                        && tabella[riga_tmp][colonna_tmp].getQuota() <= maxquota) {
                    if (iteratori.get(0).getPos_riga() != riga_tmp
                            && iteratori.get(1).getPos_riga() != riga_tmp
                            && iteratori.get(2).getPos_riga() != riga_tmp
                            && iteratori.get(4).getPos_riga() != riga_tmp) {
                        trovata = true;
                    }
                }
            }

            if (iteratore == 4) {
                if (tabella[riga_tmp][colonna_tmp].getQuota() >= (4 / (tabella[iteratori.get(0).getPos_riga()][iteratori.get(0).getPos_colonna()].getQuota() * tabella[iteratori.get(2).getPos_riga()][iteratori.get(2).getPos_colonna()].getQuota()))
                        && tabella[riga_tmp][colonna_tmp].getQuota() <= maxquota) {
                    if (tabella[riga_tmp][colonna_tmp].getQuota() >= (4 / (tabella[iteratori.get(0).getPos_riga()][iteratori.get(0).getPos_colonna()].getQuota() * tabella[iteratori.get(3).getPos_riga()][iteratori.get(3).getPos_colonna()].getQuota()))) {
                        if (iteratori.get(0).getPos_riga() != riga_tmp
                                && iteratori.get(1).getPos_riga() != riga_tmp
                                && iteratori.get(2).getPos_riga() != riga_tmp
                                && iteratori.get(3).getPos_riga() != riga_tmp) {
                            trovata = true;
                        }
                    }
                }
            }

            if (trovata == false) {
                if (colonna_tmp == maxdimcolonna) {
                    colonna_tmp = 0;
                    riga_tmp++;
                } else {
                    colonna_tmp++;
                }
            } else {

                iteratori.get(iteratore).setPos_riga(riga_tmp);
                iteratori.get(iteratore).setPos_colonna(colonna_tmp);

                if (iteratore != 4) {

                    if (primaPosizioneValida(0, 0, iteratore + 1,
                            iteratori) == true) {
                        trovata = true;
                    } else {
                        trovata = false;
                        if (colonna_tmp == maxdimcolonna) {
                            colonna_tmp = 0;
                            riga_tmp++;
                        } else {
                            colonna_tmp++;
                        }
                    }

                }

            }

        }

        if (trovata) {

            return true;
        }

        iteratori.get(iteratore).setPos_riga(maxdimriga + 10);
        iteratori.get(iteratore).setPos_colonna(100);

        return false;

    }

    public int getContatoresistemi() {
        return contatoresistemi;
    }

    public void setContatoresistemi(int contatoresistemi) {
        this.contatoresistemi = contatoresistemi;
    }

    public int getMaxdimcolonna() {
        return maxdimcolonna;
    }

    public void setMaxdimcolonna(int maxdimcolonna) {
        this.maxdimcolonna = maxdimcolonna;
    }

    public int getMaxdimriga() {
        return maxdimriga;
    }

    public void setMaxdimriga(int maxdimriga) {
        this.maxdimriga = maxdimriga;
    }

    public double getMaxquota() {
        return maxquota;
    }

    public void setMaxquota(double maxquota) {
        this.maxquota = maxquota;
    }

    public int getPuntataschedina() {
        return puntataschedina;
    }

    public void setPuntataschedina(int puntataschedina) {
        this.puntataschedina = puntataschedina;
    }

    public Vector<Sistema> getSistemi() {
        return sistemi;
    }

    public void setSistemi(Vector<Sistema> sistemi) {
        this.sistemi = sistemi;
    }

    public Scommessa[][] getTabella() {
        return tabella;
    }

    public void setTabella(Scommessa[][] tabella) {
        this.tabella = tabella;
    }


}
